package ru.bytedog.oiot.counter.bot.service.command;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.objects.Message;
import ru.bytedog.oiot.counter.bot.bean.BotAnswer;

@Slf4j
@Component
public class CommandProcessor {

    private static final String COMMAND_PREFIX = "/";
    private final ApplicationContext context;

    public CommandProcessor(ApplicationContext context) {
        this.context = context;
    }

    public BotAnswer processMessage(Message message) {
        BotCommand command = getCommand(message);
        log.debug("Для сообщения {} от {} выбран обработчик - {}", message.getText(), message.getChatId(), command.getClass().getName());
        return command.commandProcess(message);
    }


    private BotCommand getCommand(Message message) {
        if (StringUtils.isNoneEmpty(message.getText()) && !message.getText().startsWith(COMMAND_PREFIX)) {
            return context.getBean("textCommand", TextCommand.class);
        }
        return context.getBeansOfType(BotCommand.class).values().stream()
                .filter(botCommand -> botCommand.getCommand().getValue().equals(message.getText()))
                .findFirst()
                .orElse(context.getBean(DefaultCommand.class));
    }
}
